package cn.ivast.recyclerviewtest.decoration;

import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Rect;
import android.support.v7.widget.RecyclerView;
import android.view.View;

/**
 * Created by hcs on 2018/11/25.
 */
public class MyDecoration extends RecyclerView.ItemDecoration{
    private int mHeight = 5;
    private Paint paint = null;

    public MyDecoration(int mHeight) {
        this.mHeight = mHeight;
        paint = new Paint();
        paint.setColor(Color.RED);
        paint.setAntiAlias(true);
        paint.setStrokeWidth(5);
    }

    /**
     * 通过Rect为每个Item设置偏移，用于绘制Decoration。
     * @param outRect
     * @param view
     * @param parent
     * @param state
     */
    @Override
    public void getItemOffsets(Rect outRect, View view, RecyclerView parent, RecyclerView.State state) {
        super.getItemOffsets(outRect, view, parent, state);
        //拿到当前view在列表的位置
        int position = parent.getChildAdapterPosition(view);
        if (position != 0) {
            //为不是第一个item预留空间
            outRect.top = mHeight;
        }
    }

    /**
     * 通过该方法，在Canvas上绘制内容，在绘制Item之前调用。（如果没有通过getItemOffsets设置偏移的话，Item的内容会将其覆盖）
     * @param c
     * @param parent
     * @param state
     */
    @Override
    public void onDraw(Canvas c, RecyclerView parent, RecyclerView.State state) {
        super.onDraw(c, parent, state);
        int left = parent.getLeft();
        int right = parent.getRight();
        int childCount = parent.getChildCount();
        for (int i = 0; i < childCount; i++) {
            View childView = parent.getChildAt(i);
            int bottom = childView.getTop();
            int top = bottom - mHeight;
            c.drawRect(left,top,right,bottom,paint);
        }
    }
}
